<?php

namespace app\models;

use app\models\UserFiction;
use yii\db\ActiveRecord;
use Yii;

class UserFiction extends ActiveRecord{
	
	
	public static function tableName(){
		// return "shop_admin";
		return "{{%UserFiction}}";
	}
	
	public function rules()
    {
        return [
            [['uId', 'fId'], 'required'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'uId' => '用户id',
            'fId' => '小说类型id',
            'fUpdatetime' => '小说名称',
            'state' => '状态码',
        ];
    }
    
    //插入用户收藏小说的数据
    public function add($data){
        //load是php框架内部自主加载数据的函数，而validate是自主验证rules
        $user = new UserFiction();
        $user->uId = $data['uId'];
        $user->fId = $data['fId'];
        if ($user->save()) {
            return true;
        }
        return false;
    }
    
    //查询用户收藏的小说
    public function getByuId($uId){
    	$data = self::find()->select(['fId'])->where('uId = :uId and state = :state',[':uId'=>$uId, ':state'=>'1'])->asArray()->all();
    	return $data;
    }

    //查找是否存在这个记录
    public function checkOveruIdfId($data){
        $data = self::find()->select(['uId'])->where('uId = :uId and fId = :fId',[':uId'=>$data['uId'], 'fId'=>$data['fId']])->asArray()->one();
        if(!empty($data)){
            return true;
        }
        return false;
    }

    //查看某部小说是否被用户所收藏
    public function checkByuIdfId($data){
    	$data = self::find()->select(['uId'])->where('uId = :uId and fId = :fId and state = :state',[':uId'=>$data['uId'], 'fId'=>$data['fId'], ':state'=>'1'])->asArray()->one();
    	if(!empty($data)){
    		return true;
    	}
        return false;
    }

    //取消收藏时将state改为0
    public function updateOffState($data){
        $key = [
        	'uId' => $data['uId'],
            'fId' => $data['fId'],
        ];
        $changedata = [
            'state' => 0,
        ];
        $result = UserFiction::updateAll($changedata,$key);
        if( $result == 1 ){
            return true;
        }
        return false;
    }

    //收藏将state改为1
    public function updateOnState($data){
        $key = [
            'uId' => $data['uId'],
            'fId' => $data['fId'],
        ];
        $changedata = [
            'state' => 1,
        ];
        $result = UserFiction::updateAll($changedata,$key);
        if( $result == 1 ){
            return true;
        }
        return false;
    }
}
